package com.common.config.pool;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class AsyncPoolConfig {
    @Bean(name = "asyncThreadPool")
    public Executor asyncThreadPool() {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);        // 核心线程数（稳定运行的线程数）
        executor.setMaxPoolSize(5);        // 最大线程数（峰值线程数，建议 < 连接池最大连接数）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 队列满时，由调用方线程执行（避免任务丢失）
        executor.setThreadNamePrefix("async-thread-pool-" + atomicInteger.getAndIncrement()); // 线程名前缀，方便排查日志
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);  // 使用阿里巴巴的TTL工具类，使线程池中的线程继承父线程的TTL
    }
}
